package com.study.springboottest.thread;

public class AAndBJob implements Runnable {

    private final BackAccount backAccount = new BackAccount();

    public static void main(String[] args) {
        AAndBJob aAndBJob = new AAndBJob();
        Thread A = new Thread(aAndBJob);
        Thread B = new Thread(aAndBJob);
        A.setName("A");
        B.setName("B");
        A.start();
        B.start();
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            check(10);
            if (backAccount.getBalance() < 0) {
                System.out.println("余额不足");
            }
        }
    }

    public synchronized void check(int amount) {
        if (backAccount.getBalance() > amount) {
            System.out.println(Thread.currentThread().getName() + "检查余额");
            try {
                System.out.println(Thread.currentThread().getName() + "去睡觉");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "醒来");
            backAccount.withdraw(amount);
            System.out.println(Thread.currentThread().getName() + "取钱结束");
        } else {
            System.out.println("sorry no enough for" + Thread.currentThread().getName());
        }
    }
}
